<template>
  <div class="storeUserModify common-container">
    <div class="common-top">
      <span class="left">
        <span class="go-back" @click.stop="$router.go(-1)">返回</span>
      </span>
      <el-button type="primary" @click="save">保存</el-button>
    </div>
    <div class="common-bot">
      <div class="modify-bot">
        <el-form :model="form" label-width="100px">
          <el-form-item required label="名称" style="width: 30%">
            <el-input v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item required label="类型" style="width: 30%">
            <el-select v-model="form.storeType" placeholder="请选择">
              <el-option
                v-for="item in storeTypeOptions"
                :key="item.value"
                :label="item.text"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item required label="客户账户" style="width: 30%">
            <el-select
              v-model="form.userId"
              filterable
              remote
              reserve-keyword
              placeholder="请输入关键词"
              :remote-method="remoteMethod"
              :loading="loading"
            >
              <el-option
                v-for="item in userList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item required label="连锁" style="width: 30%">
            <el-select
              v-model="form.chainId"
              filterable
              remote
              reserve-keyword
              placeholder="请输入关键词"
              :remote-method="remoteMethodForChain"
              :loading="loading"
            >
              <el-option
                v-for="item in chainList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item required label="省份" style="width: 45%">
            <el-cascader
              ref="cascader"
              :props="{ checkStrictly: true }"
              :options="areaSelectData"
              class="full-width"
              size="large"
              v-model="form.province"
              placeholder="请选择"
            />
          </el-form-item>
          <el-form-item required label="城市" style="width: 45%">
            <el-cascader
              ref="cascader"
              :props="{ checkStrictly: true }"
              :options="areaSelectData"
              class="full-width"
              size="large"
              v-model="form.city"
              placeholder="请选择"
            />
          </el-form-item>
          <el-form-item required label="经度" style="width: 30%">
            <el-input v-model="form.longitude"></el-input>
          </el-form-item>
          <el-form-item required label="纬度" style="width: 30%">
            <el-input v-model="form.latitude"></el-input>
          </el-form-item>
          <el-form-item required label="排序" style="width: 30%">
            <el-input v-model="form.queue"></el-input>
          </el-form-item>
          <el-form-item label="会员等级是否按积分自动" style="width: 30%">
            <el-switch v-model="form.vipAuto"></el-switch>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>
<script>
import UploadFile from "@/components/uploadFile";
import {
  provinceAndCityData,
  CodeToText,
  TextToCode,
} from "element-china-area-data";
import ManaApi from "@/api/index";
import maps from "qqmap";

export default {
  name: "storeUserModify",
  components: { UploadFile },
  data() {
    return {
      chainList: [],
      areaSelectData: provinceAndCityData,
      userList: [],
      genderOptions: [
        {
          label: "男",
          value: "male",
        },
        {
          label: "女",
          value: "female",
        },
      ],
      vipOptions: [
        {
          label: "普通版",
          value: "0",
        },
      ],
      storeTypeOptions: [],
      form: {
        chainId: 0,
        city: "",
        formId: 0,
        latitude: 0,
        longitude: 0,
        name: "",
        province: "",
        queue: 0,
        storeType: "",
        userId: 0,
        vipAuto: true,
      },
      roleOptions: [
        {
          label: "老板",
          value: "boss",
        },
        {
          label: "员工",
          value: "employee",
        },
      ],
      loading: false,
    };
  },
  methods: {
    codeAddress(address) {
      return new Promise((resolve, reject) => {
        //对指定地址进行解析
        this.myGeocoder.getLocation(address);
        //设置服务请求成功的回调函数
        this.myGeocoder.setComplete((result) => {
          console.log(result);
          resolve(result);
        });
        //若服务请求失败，则运行以下函数
        this.myGeocoder.setError(() => {
          this.$message.error("地址信息不正确");
          reject();
        });
      }).catch((err) => {
        reject();
      });
    },
    initMap() {
      return new Promise((resolve, reject) => {
        maps.init("3OQBZ-L7R6D-YCD46-PJJYB-FPAS7-U5BTZ", () => {
          this.myGeocoder = new qq.maps.Geocoder();
          resolve();
        });
      }).catch((err) => {
        reject();
      });
    },
    async remoteMethod(query) {
      if (query !== "") {
        this.loading = true;
        await this.getUserList(query);
        this.loading = false;
      } else {
        await this.getUserList();
        this.loading = false;
      }
    },
    async remoteMethodForChain(query) {
      if (query !== "") {
        this.loading = true;
        await this.getChain(query);
        this.loading = false;
      } else {
        await this.getChain();
        this.loading = false;
      }
    },
    getChain(query = "") {
      return new Promise((resolve, reject) => {
        ManaApi.chain
          .list({
            limit: this.$normalMaxLimit,
            page: 0,
            keyword: query,
          })
          .then((res) => {
            this.chainList = res.data;
            resolve();
          })
          .catch((err) => {
            reject();
          });
      });
    },
    getUserList(query = "") {
      return new Promise((resolve, reject) => {
        ManaApi.storeUserMana
          .userList({
            limit: this.$normalMaxLimit,
            page: 0,
            keyword: query,
          })
          .then((res) => {
            this.userList = res.data;
            resolve();
          })
          .catch((err) => {
            reject();
          });
      });
    },
    uploadSuc(data) {
      this.$set(this.form, "avatar", data.url);
      console.log(data);
    },
    checkInfo() {
      if (String(this.form.name).trim() == "") {
        this.$message.error("请填写名称");
        return false;
      }
      return true;
    },
    async save() {
      if (!this.checkInfo()) {
        return;
      }
      let form = JSON.parse(JSON.stringify(this.form));
      form.city = String(form.city);
      form.province = String(form.province);
      let addStr = "";
      this.form.city.forEach((item) => {
        addStr += CodeToText[item];
      });
      let addressRes = await this.codeAddress(addStr);
      console.log(addressRes);
      form.latitude = addressRes.detail.location.lat;
      form.longitude = addressRes.detail.location.lng;
      ManaApi.store.edit(form).then((res) => {
        if (res.code == 200) {
          this.$message.success("操作成功");
          this.$router.go(-1);
        }
      });
    },
    getInfo() {
      ManaApi.store
        .detail({
          targetId: this.$route.query.id,
        })
        .then((res) => {
          let city = res.data.city ? res.data.city.split(",") : [];
          this.form = {
            chainId: res.data.chain ? res.data.chain.id : null,
            city,
            formId: res.data.id,
            latitude: res.data.latitude,
            longitude: res.data.longitude,
            name: res.data.name,
            province: res.data.province,
            queue: res.data.queue,
            storeType: res.data.storeType,
            userId: res.data.storeUserId,
            vipAuto: res.data.vipAuto,
          };
        });
    },
    getConstant() {
      return new Promise((resolve, reject) => {
        ManaApi.constant
          .all({})
          .then((res) => {
            this.storeTypeOptions = res.data.StoreType;
            resolve();
          })
          .catch((err) => {
            reject();
          });
      });
    },
  },
  async mounted() {
    await this.getUserList();
    await this.getChain();
    await this.getConstant();
    await this.initMap();
    if (this.$route.query.type == "edit") {
      this.getInfo();
    }
  },
};
</script>
<style lang="scss" scoped>
.storeUserModify {
}
</style>